<?php
class MysqlDriver
{
    public $config = array();
    public $conn = null;
    public $result = null;
    public $data = null;
    public $error = null;

    function __construct()
    {

    }


    public function getConnect($db_config = array())
    {
        if ($this->conn == null) {
            $this->getConfig($db_config);
            $this->conn = @mysql_connect($this->config["host"], $this->config["user"], $this->config["pass"]) or die("Không thể kết nối đến server");
            if (!self::useDB()) {
                return false;
            }
            mysql_query('SET NAMES "' + $this->config["charset"] + '"', $this->conn);
            return true;
        }
    }

    private function useDB()
    {
        if (!@mysql_select_db($this->config["databaseName"], $this->conn)) {
            $this->error = 'Cannot select database';
            return false;
        } else {
            return true;
        }
    }

    private function getConfig($db_config = array())
    {
        if (count($db_config) > 0 && $db_config["connectString"] != null && preg_match("/mysql:host=(.*);dbname=(.*)/", $db_config["connectString"], $matches)) {
            $this->config["user"] = $db_config["username"];
            $this->config["pass"] = $db_config["password"];
            $this->config["host"] = $matches[1];
            $this->config["databaseName"] = $matches[2];
            $this->config["charset"] = $db_config["charset"];
        }
    }

    public function disconnect()
    {
        if ($this->conn) {
            mysql_close($this->conn);
            $this->conn = false;
        }
    }

    public function query($sql)
    {
        if ($this->conn)
            return $this->result = @mysql_query($sql, $this->conn);
        else
            return null;
    }

    public function getId()
    {
        if ($this->conn)
            return mysql_insert_id();
        else
            return null;
    }

    public function find($sql)
    {
        if ($this->conn) {
            $this->data = array();
            $this->query($sql, $this->conn);
            if ($this->count() > 0) {
                while ($row = @mysql_fetch_object($this->result)) {
                    $this->data[] = $row;
                }
            }
            return $this->data;
        } else
            return null;
    }

    public function count()
    {
        if ($this->conn)
            return @mysql_num_rows($this->result);
        else
            return 0;
    }

}
